﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using NHibernate.Criterion;
using VictorBlaga.DocumentManagement.Core.Models;
using VictorBlaga.DocumentManagement.Core.Models.Repositories;

namespace VictorBlaga.DocumentManagement.Infrastructure.DataAccess
{
    public class TeamRepository:NHibernateRepository, ITeamRepository
    {
        public Team[] GetAll()
        {
            var query = Session.CreateQuery("from Team t order by t.Name asc");
            return query.List<Team>().ToArray();
        }

        public Team GetByID(int id)
        {
            var team = (Team) Session.CreateCriteria(typeof (Team)).Add(Expression.Eq("ID", id)).UniqueResult();
            return team;
        }

        public void Save(Team item)
        {
            Session.Save(item);
        }

        public void Delete(Team item)
        {
            Session.Delete(item);
        }

        public bool IsUniqueName(int id, string name)
        {
            var query = Session.CreateQuery("select count(t) from Team t where t.Name=:name and ID<>:id");
            query.SetString("name", name.ToLower());
            query.SetInt32("id", id);

            var result = query.UniqueResult();

            return (long) result == 0;
        }
    }
}
